package handlers;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;

public class HTTP {
	public static final String CRLF = "\r\n";
	
	public static String header(int rc, String fname, byte[] raw){
		String s = "HTTP/1.1";
		switch(rc){
			case 200:
				s = s + "200 OK" + CRLF;
				break;
			case 500:
				s = s + "500 Internal Server Error" + CRLF;
				break;
			case 501:
				s = s + "501 Not Implemented" + CRLF;
				break;
		}
		s = s + "Connection: close" + CRLF;
		s = s + "Server: Wazzup" + CRLF;
		s = s + "Content-Type: " + FileHandler.getMime(fname) + CRLF;
		s = s + "Content-Disposition: attachment; filename=" + fname + CRLF;
		s = s + "Content-Length: " + raw.length + CRLF;
		s = s + CRLF;
		return s;
	}
	
	public static String search(String param, int port) throws UnknownHostException{
		HashMap<String, String> paramMap = new HashMap<String, String>();
		String result = "";
		if (!param.contains("&")){
			String pair = param.substring(param.lastIndexOf("?")+1);
			paramMap.put(pair.split("=")[0], pair.split("=")[1]);
		}
		else{
			String[] pairs = param.substring(param.lastIndexOf("?")+1).split("&");
			for(String p: pairs){
				paramMap.put(p.split("=")[0], p.split("=")[1]);
			}
		}
		
		ArrayList<File> files = FileHandler.getFiles(paramMap.get("name"));
		result = result + "{ \"id\": \""+ paramMap.get("id")+"\"," + CRLF;
		result = result + "\"files\":" + CRLF;
		result = result + "[" + CRLF;
		int i = 0;
		for (File f: files){
			i++;
			if(i == files.size()){
				result = result + "{\"ip\":\"" + Inet4Address.getLocalHost().getHostAddress() + "\", \"port\":\"" + port +"\", \"name\":\"" + f.getName() + "\"}" + CRLF;
			}
			else{
				result = result + "{\"ip\":\"" + Inet4Address.getLocalHost().getHostAddress() + "\", \"port\":\"" + port +"\", \"name\":\"" + f.getName() + "\"}," + CRLF;
			}
		}
		result = result + "]" + CRLF;
		result = result + "}";
		return result;

	}
	
	public static void download(String filename, DataInputStream dis){
		
	}
	
	public static void upload(String path, DataOutputStream dos){
		String param = path.substring(path.lastIndexOf("?")+1);
		String[] pair = param.split("=");
		String fname = null;
		byte[] raw = null;
		if (pair[0].equals("fullname")){
			fname = pair[1];
			raw = FileHandler.getRawData(fname);
			String header = header(200, fname, raw);
			try {
				dos.writeBytes(header);
				dos.write(raw);
				dos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}		
	}
	
	

}
